from typing import Optional, Dict, Any, List
from enum import Enum
from pydantic import BaseModel, Field, validator

class AudioFormat(str, Enum):
    """音频格式枚举"""
    MP3 = "mp3"
    WAV = "wav"
    OGG = "ogg"
    FLAC = "flac"
    M4A = "m4a"

class TtsVoice(str, Enum):
    """TTS语音类型枚举"""
    FEMALE = "female"
    MALE = "male"
    NEUTRAL = "neutral"

class TtsRequest(BaseModel):
    """文字转语音请求模型"""
    text: str = Field(..., description="需要转换为语音的文本")
    user: str = Field(..., description="用户ID")
    voice: Optional[TtsVoice] = Field(TtsVoice.NEUTRAL, description="语音类型")
    format: Optional[AudioFormat] = Field(AudioFormat.MP3, description="音频格式")
    speed: Optional[float] = Field(1.0, description="语速，范围0.5-2.0")
    
    @validator('text')
    def text_not_empty(cls, v):
        """验证文本不为空"""
        if not v or not v.strip():
            raise ValueError("文本内容不能为空")
        return v.strip()
    
    @validator('speed')
    def speed_in_range(cls, v):
        """验证语速在合理范围内"""
        if v < 0.5 or v > 2.0:
            return 1.0  # 如果超出范围，使用默认值
        return v

class TtsResponse(BaseModel):
    """文字转语音响应模型"""
    task_id: str = Field(..., description="任务ID")
    audio_url: str = Field(..., description="音频文件URL")
    text: str = Field(..., description="原文本")
    created_at: int = Field(..., description="创建时间戳")

class SttRequest(BaseModel):
    """语音转文字请求模型"""
    user: str = Field(..., description="用户ID")
    # 注意：文件会通过multipart/form-data上传，不在JSON模型中

class SttResponse(BaseModel):
    """语音转文字响应模型"""
    task_id: str = Field(..., description="任务ID")
    text: str = Field(..., description="转录文本")
    language: Optional[str] = Field(None, description="检测到的语言")
    created_at: int = Field(..., description="创建时间戳")
    segments: Optional[List[Dict[str, Any]]] = Field(None, description="文本分段信息")

class AudioTaskStatus(str, Enum):
    """音频任务状态枚举"""
    PENDING = "pending"
    PROCESSING = "processing"
    COMPLETED = "completed"
    FAILED = "failed"

class AudioTaskResponse(BaseModel):
    """音频任务状态响应模型"""
    task_id: str = Field(..., description="任务ID")
    status: AudioTaskStatus = Field(..., description="任务状态")
    created_at: int = Field(..., description="创建时间戳")
    completed_at: Optional[int] = Field(None, description="完成时间戳")
    result: Optional[Dict[str, Any]] = Field(None, description="任务结果")
    error: Optional[str] = Field(None, description="错误信息，仅当任务失败时")
